var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
const bodyParser = require('body-parser')
const { existSend } = require('./utils/resend');
const { httpLogger } = require('./log/log')
const { setPoolConnection } = require('./utils/mysql/connect')


var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(httpLogger); // 日志中间件
app.use(existSend); // 重构返回数据格式

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser('keyboard cat'));

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.use(session({
  name: 'connect.sid_1',
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 600000 , httpOnly: true, secure: false, path: '/'}
}))

app.use('/', setPoolConnection)
app.use('/api', indexRouter);
app.use('/api/users',usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.log.info('404')
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.log.error(err,err.message)
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
